const state = {
  configs: {},
  currentConfigFile: null
}

const mutations = {
  SET_CONFIG(state, { key, value }) {
    state.configs[key] = value
  },
  
  SET_CONFIGS(state, configs) {
    state.configs = configs
  },
  
  SET_CURRENT_CONFIG_FILE(state, file) {
    state.currentConfigFile = file
  }
}

const actions = {
  async importConfig({ commit, dispatch }) {
    if (!window.electronAPI) return
    
    const result = await window.electronAPI.dialog.openFile({
      title: '导入配置',
      filters: [
        { name: 'JSON Files', extensions: ['json'] },
        { name: 'All Files', extensions: ['*'] }
      ],
      properties: ['openFile']
    })
    
    if (!result.canceled && result.filePaths.length > 0) {
      try {
        const fs = require('fs')
        const content = fs.readFileSync(result.filePaths[0], 'utf8')
        const configs = JSON.parse(content)
        
        commit('SET_CONFIGS', configs)
        commit('SET_CURRENT_CONFIG_FILE', result.filePaths[0])
        
        dispatch('ui/showLoading', '正在导入配置...', { root: true })
        
        setTimeout(() => {
          dispatch('ui/hideLoading', null, { root: true })
          dispatch('applyConfigs')
        }, 500)
        
        return { success: true }
      } catch (error) {
        console.error('Failed to import config:', error)
        return { success: false, error: error.message }
      }
    }
  },
  
  async exportConfig({ state }) {
    if (!window.electronAPI) return
    
    const result = await window.electronAPI.dialog.saveFile({
      title: '导出配置',
      defaultPath: 'linkverify-config.json',
      filters: [
        { name: 'JSON Files', extensions: ['json'] },
        { name: 'All Files', extensions: ['*'] }
      ]
    })
    
    if (!result.canceled && result.filePath) {
      try {
        const fs = require('fs')
        const content = JSON.stringify(state.configs, null, 2)
        fs.writeFileSync(result.filePath, content, 'utf8')
        
        return { success: true, filePath: result.filePath }
      } catch (error) {
        console.error('Failed to export config:', error)
        return { success: false, error: error.message }
      }
    }
  },
  
  saveConfig({ state }) {
    localStorage.setItem('linkverify-configs', JSON.stringify(state.configs))
  },
  
  loadConfig({ commit }) {
    const saved = localStorage.getItem('linkverify-configs')
    if (saved) {
      try {
        const configs = JSON.parse(saved)
        commit('SET_CONFIGS', configs)
      } catch (e) {
        console.error('Failed to load config:', e)
      }
    }
  },
  
  updateConfig({ commit }, { key, value }) {
    commit('SET_CONFIG', { key, value })
  },
  
  applyConfigs({ state, dispatch }) {
    Object.entries(state.configs).forEach(([module, config]) => {
      dispatch(`${module}/applyConfig`, config, { root: true }).catch(() => {})
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}